<template>
	<div>
		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>用户管理</el-breadcrumb-item>
			<el-breadcrumb-item>用户列表</el-breadcrumb-item>
		</el-breadcrumb>
		<el-card class="box-card">
			<el-row :gutter="20">
				<el-col :span="7">
					<el-input placeholder="请输入内容" clearable @clear="getUserList" v-model="queryInfo.query">
						<el-button @click="query" slot="append" icon="el-icon-search"></el-button>
					</el-input>
				</el-col>
				<el-col :span="3">
					<el-button type="primary" @click="dialogFormVisible = true">添加用户</el-button>
				</el-col>
			</el-row>
			<!-- close弹出框关闭触发事件 -->
			<el-dialog title="添加用户" @close="addDialogClose" :visible.sync="dialogFormVisible" width="50%">
				<el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px"
					class="demo-ruleForm">
					<el-form-item label="用户名" prop="username">
						<el-input v-model="addForm.username"></el-input>
					</el-form-item>
					<el-form-item label="密码" prop="password">
						<el-input v-model="addForm.password"></el-input>
					</el-form-item>
					<el-form-item label="手机号码" prop="mobile">
						<el-input v-model="addForm.mobile"></el-input>
					</el-form-item>
					<el-form-item label="邮箱" prop="email">
						<el-input v-model="addForm.email"></el-input>
					</el-form-item>
				</el-form>
				<div slot="footer" class="dialog-footer">
					<el-button @click="dialogFormVisible = false">取 消</el-button>
					<el-button type="primary" @click="addUser">确 定</el-button>
				</div>
			</el-dialog>
			<el-table :stripe='true' :data="userList" border>
				<el-table-column type="index" label="#" width="30">
				</el-table-column>
				<el-table-column prop="username" label="姓名">
				</el-table-column>
				<el-table-column prop="email" label="邮箱">
				</el-table-column>
				<el-table-column prop="mobile" label="电话">
				</el-table-column>
				<el-table-column prop="role_name" label="角色" width="180">
				</el-table-column>
				<el-table-column prop="create_time" label="状态">
					<template slot-scope="scope">
						<!-- scope.row每一行数据 -->
						<el-switch v-model="scope.row.mg_state" @change="switchChange(scope.row)"></el-switch>
					</template>
				</el-table-column>
				<el-table-column label="操作">
					<template slot-scope="scope">
						<!-- 修改按钮 -->
						<el-button type="primary" icon="el-icon-edit" size="small" @click="amend(scope.row)">
						</el-button>
						<!-- 删除按钮 -->
						<el-button type="warning" icon="el-icon-delete" size="small" @click="deleteUser(scope.row.id)">
						</el-button>
						<!-- 分配角色按钮 -->
						<el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
							<el-button type="danger" icon="el-icon-setting" size="small" @click="allocation(scope.row)">
							</el-button>
						</el-tooltip>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
				:current-page="queryInfo.pagenum" :page-size="queryInfo.pagesize" :page-sizes="[1, 2, 3, 5]"
				layout="total, sizes, prev, pager, next, jumper" :total="total">
			</el-pagination>
		</el-card>
		<!-- 修改用户信息表单 -->
		<el-dialog title="修改用户信息" @close="addDialogClose" :visible.sync="amendFormVisible">
			<el-form :model="amendFrom" :rules="addFormRules" ref="addFormRef" label-width="100px"
				class="demo-ruleForm">
				<el-form-item label="用户名">
					<el-input disabled v-model="amendFrom.username"></el-input>
				</el-form-item>
				<el-form-item label="邮箱" prop="email">
					<el-input v-model="amendFrom.email"></el-input>
				</el-form-item>
				<el-form-item label="手机" prop="mobile">
					<el-input v-model="amendFrom.mobile"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="amendFormVisible = false">取 消</el-button>
				<el-button type="primary" @click="amendPut">确 定</el-button>
			</div>
		</el-dialog>
		<!-- 修改用户信息表单结束 -->
		<!-- 分配角色allocation -->
		<el-dialog title="提示" @close="allocationing" :visible.sync="allocationDialog" width="50%">
			<div class="allocation">
				<p>当前的用户：{{userInfo.username}}</p>
				<p>当前的角色：{{userInfo.role_name}}</p>
				<p>权限列表：<el-select v-model="selectRoleId" placeholder="请选择">
						<el-option v-for="item in roletList" :key="item.id" :label="item.roleName" :value="item.id">
						</el-option>
					</el-select>
				</p>
			</div>
			<span slot="footer" class="dialog-footer">
				<el-button @click="allocationDialog = false">取 消</el-button>
				<el-button type="primary" @click="allocationOk">确 定</el-button>
			</span>
		</el-dialog>
	</div>

</template>
<script>
	export default {
		data() {
			// 验证邮箱
			var checkEmail = (vale, value, cb) => {
				const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[ a-zA-Z0-9_-])+/
				if (regEmail.test(value)) {
					return cb()
				}
				cb(new Error('请输入合法的邮箱'))
			}
			//验证手机号
			var checkMobile = (vale, value, cb) => {
				const regMobile = /^(0|86|17951)?(13[0-9]|15[O12356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
				if (regMobile.test(value)) {
					return cb()
				}
				cb(new Error('请输入正确的手机号码'))
			}
			return {
				userInfo: {},
				allocationDialog: false,
				addForm: {
					username: '',
					password: '',
					mobile: '',
					email: ''
				},
				addFormRules: {
					username: [{
							required: true,
							message: '请输入用户名',
							trigger: 'blur'
						},
						{
							min: 3,
							max: 10,
							message: '长度在 3 到 10 个字符',
							trigger: 'change'
						}
					],
					password: [{
							required: true,
							message: '请输入密码',
							trigger: 'blur'
						},
						{
							min: 6,
							max: 15,
							message: '长度在 6 到 15 个字符',
							trigger: 'blur'
						}
					],
					email: [{
							required: true,
							message: '请输入邮箱',
							trigger: 'blur'
						},
						{
							validator: checkEmail,
							trigger: 'blur'
						}
					],
					mobile: [{
							required: true,
							message: '请输入手机号码',
							trigger: 'blur'
						},
						{
							validator: checkMobile,
							trigger: 'blur'
						}
					]
				},
				userList: [],
				dialogFormVisible: false, //控制添加用户对话框的显示与隐藏
				amendFormVisible: false,
				total: 0,
				queryInfo: {
					query: '',
					pagenum: 1,
					pagesize: 2
				},
				formUser: {
					name: '',
					region: ''
				},
				formLabelWidth: '120px',
				amendFrom: {
					username: '',
					email: '',
					mobile: ''
				},
				roletList: [],
				selectRoleId:'',
				UserID:0
			}
		},
		created() {
			this.getUserList()
		},
		methods: {
			//清空select框数据事件
			allocationing(){
				this.selectRoleId=''
			},
			//分配角色确定事件
			async allocationOk(){
				if(!this.selectRoleId)return this.$message.error('请选择角色')
				const {data:res} = await this.$http.put(`users/${this.UserID}/role`,{rid:this.selectRoleId})
				if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
				this.$message.success('分配角色成功！')
				this.getUserList()
				this.allocationDialog = false
			},
			// 分配角色弹框事件
			async allocation(row) {
				this.UserID = row.id
				this.userInfo = row
				const {
					data: res
				} = await this.$http.get(`roles`)
				if (res.meta.status !== 200) return this.$message.error('获取角色列表失败！')
				this.roletList = res.data
				this.allocationDialog = true
			},
			//删除用户
			async deleteUser(Userid) {
				await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(async () => {
					var {
						data: res
					} = await this.$http.delete('users/' + Userid)
					if (res.meta.status !== 200) return this.$message.error('删除失败,请重试！！')
					this.$message({
						type: 'success',
						message: '删除成功!'
					});
					this.getUserList();
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});

			},
			// 修改用户信息
			amendPut() {
				this.$refs.amendFormRef.validate(async res => {
					if (!res) return;
					const {
						data: msg
					} = await this.$http.put('users/' + this.amendFrom.id, {
						email: this.amendFrom.email,
						mobile: this.amendFrom.mobile
					})
					if (msg.meta.status !== 200) return this.$message.error('修改失败');
					this.$message({
						message: '修改成功',
						type: 'success'
					});
					this.getUserList();
					this.amendFormVisible = false
				})
			},
			// 打开修改对话框
			amend(msg) {
				this.amendFrom = msg
				this.amendFormVisible = true;
			},
			// 关闭对话框时重置表单
			addDialogClose() {
				this.$refs.addFormRef.resetFields();
			},
			// 添加用户对话框
			addUser() {
				this.$refs.addFormRef.validate(async vali => {
					if (!vali) return;
					var {
						data: msg
					} = await this.$http.post('users', this.addForm)
					if (msg.meta.status !== 201) return this.$message.error(msg.meta.msg)
					this.$message({
						message: '添加用户成功',
						type: 'success'
					});
					this.getUserList();
					this.dialogFormVisible = false;
				})
			},
			// 获取用户数据
			async getUserList() {
				const {
					data: res
				} = await this.$http.get('users', {
					params: this.queryInfo
				})
				if (res.meta.status !== 200) return this.$message.error('获取用户列表失败!')
				this.userList = res.data.users
				this.total = res.data.total
			},
			handleSizeChange(newSize) {
				this.queryInfo.pagesize = newSize;
				this.getUserList();
			},
			handleCurrentChange(newCurrent) {
				this.queryInfo.pagenum = newCurrent;
				this.getUserList();
			},
			async switchChange(scope) {
				var smsg = await this.$http.put('users/' + scope.id + '/state/' + scope.mg_state);
				var {
					data: msg
				} = smsg
				if (msg.meta.status !== 200) {
					scope.mg_state = !scope.mg_state;
					return this.$message.error('更改失败！！')
				};
				this.$message({
					message: '修改成功',
					type: 'success'
				});
			},
			query() {
				this.getUserList();
			}
		}
	}
</script>

<style>
	.text {
		font-size: 14px;
	}

	.item {
		padding: 18px 0;
	}

	.box-card {
		width: 100%;
	}

	.el-table {
		margin-top: 15px;
		font-size: 12px;
		width: 1054px;
	}

	.cell {
		width: 180px;
	}

	.allocation p {
		line-height: 30px;
	}
</style>
